const crypto = require('digest.js')
const base64 = require('base64-arraybuffer')
const Digest = require('./digest')

function createCommonToken(params) {
    const access_key =  base64.decode(params.author_key)
    const version = params.version
    let res = 'userid' + '/' + params.user_id
    const et = Math.ceil((Date.now() + 365 * 24 * 3600 * 1000) / 1000)   
    const method = 'sha1'
    const key = et + "\n" + method + "\n" + res + "\n" + version
    
    var sha1hmac = new Digest.HMAC_SHA1();
    sha1hmac.setKey(access_key);
    sha1hmac.update(key);
    let hmac = sha1hmac.finalize();
    let sign = base64.encode(hmac);

    res = encodeURIComponent(res)
    sign = encodeURIComponent(sign)
    const token = `version=${version}&res=${res}&et=${et}&method=${method}&sign=${sign}`

    return token
}

module.exports = {
  createCommonToken
};


